package com.ruoyi.web.controller.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Test.HttpsService;
import com.ruoyi.common.utils.Test.MD5Util;
import com.ruoyi.common.utils.Test.PrivacyBindBodyAxb;
import com.ruoyi.system.domain.POrder;
import com.ruoyi.system.domain.PStoreOrder;
import com.ruoyi.system.domain.bo.POrderBo;
import com.ruoyi.system.domain.bo.PStoreOrderBo;
import com.ruoyi.system.mapper.POrderMapper;
import com.ruoyi.system.service.IPOrderService;
import com.ruoyi.system.service.IPStoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @Description: 咨询订单监听器
 * @Author: wk
 * @Date: 2022/8/15 10:16
 * @Version: 1.0
 */
@Component
@Slf4j
public class RedisListener extends KeyExpirationEventMessageListener {
    @Resource
    private POrderMapper orderMapper;

    @Resource
    private IPStoreOrderService ipStoreOrderService;

    @Resource
    private IPOrderService ipOrderService;

    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("处理过期订单:"+key);
        if (StringUtils.isNotBlank(key) && key.contains(PublishConstants.TIMING_KEY)) {
            String orderId = key.split(":")[1];
            System.out.println("订单时间结束:"+ orderId);

            // 咨询订单结束
            POrder pOrder = orderMapper.selectByOrderNo(orderId);
            if ("1".equals(pOrder.getOrderStatus())) {
                Date now = new Date();
                long waitMinutes = DateUtils.differentMinutesByMillisecond(pOrder.getStartTime(), now);
                if (Integer.parseInt(String.valueOf(waitMinutes)) >= Integer.parseInt(pOrder.getTimeSize())) {
                    POrderBo bo = BeanUtil.toBean(pOrder, POrderBo.class);
                    ipOrderService.paySuccessCallback(bo);
                    log.info("咨询订单{},结束更新订单状态", orderId);
                }
            }

        }
        if (StringUtils.isNotBlank(key) && key.contains(PublishConstants.ORDER_AUTO_CANCEL_KEY)) { //咨询订单
            String orderId = key.split(":")[1];
            if (StringUtils.isNotBlank(orderId)) {
                // 超过预约时间的订单，重新下单
                POrder pOrder = orderMapper.selectByOrderNo(orderId);
                if("0".equals(pOrder.getOrderStatus())){
                    pOrder.setOrderStatus("4");
                    int res = orderMapper.updateById(pOrder);
                    if (res > 0) {
                        log.info("咨询订单{}，超时，重新下单", orderId);
                    } else {
                        log.info("咨询订单重新下单失败！");
                    }
                }

            }
        }
        if (StringUtils.isNotBlank(key) && key.contains(PublishConstants.ORDERS_AUTO_CANCEL_KEY)) { //商城订单
            String orderId = key.split(":")[1];
            if (StringUtils.isNotBlank(orderId)) {
                List<PStoreOrder> list =  ipStoreOrderService.shopOrderDetail(orderId);
                for (PStoreOrder order : list) {
                    if("4".equals(order.getStatus())){
                        order.setStatus("7");
                        PStoreOrderBo update = BeanUtil.toBean(order, PStoreOrderBo.class);
                        ipStoreOrderService.updateByBo(update);
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(key) && key.contains(PublishConstants.ASK_ORDER_KEY)) { //绑定虚拟拨号
            String orderId = key.split(":")[1];
            if (StringUtils.isNotBlank(orderId)) {
                POrder pOrder = orderMapper.selectMyById(Long.valueOf(orderId));
                pOrder = orderMapper.selectByOrderNo(pOrder.getOrderNo());
                try {
                    deptList(Integer.parseInt(pOrder.getTimeSize()),pOrder.getPhone(),pOrder.getPhones());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String  deptList(int time, String phone,String phone1) throws Exception {
        Integer miao = null;
        PrivacyBindBodyAxb bindBodyAxb = new PrivacyBindBodyAxb();
        String str = "13041430152";
        /** AXB模式小号绑定接口地址*/
        String url = "https://101.37.133.245:11008/voice/1.0.0/middleNumberAXB";
        /** 设定绑定的隐私小号*/
        String trumpet = str;
        bindBodyAxb.setMiddleNumber(trumpet);
        /** 设定与该隐私小号绑定的号码A*/
        bindBodyAxb.setBindNumberA(phone1);//专家
        /** 设定与该隐私小号绑定的号码B*/
        bindBodyAxb.setBindNumberB(phone);//用户
        /** 设置是否开启通话录音  1:开启，0:关闭*/
        bindBodyAxb.setCallRec(1);
        /** 设置绑定关系有效时长 ,为空表示绑定关系永久，单位:秒*/
        //计算剩余时间秒 按照当前时间
        bindBodyAxb.setMaxBindingTime(time*60);
        //Date date = new Date();
        //SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //String format = s.format(new Date());
        ////根据订单号查询预约时间
        //Date gettime = date;
        //if(null==gettime){
        //
        //}else {
        //    String format1 = s.format(gettime);
        //    long b = s.parse(format).getTime();
        //    long a = s.parse(format1).getTime();
        //    int c = (int) ((a - b) / 1000);
        //    bindBodyAxb.setMaxBindingTime(c);
        //}
        /** 设置是否透传主叫的号码到A  0:不透传; 1: 透传，不填默认不透传*/
        bindBodyAxb.setPassthroughCallerToA(1);
        /** 设置是否透传主叫的号码到B  0:不透传; 1: 透传，不填默认不透传*/
        bindBodyAxb.setPassthroughCallerToB(1);
        //提示结束时间
        bindBodyAxb.setMaxCallDuration(1800);
//        /** 设置用于接收呼叫结果的服务地址*/
        bindBodyAxb.setCallbackUrl("https://zhjt.cnshangji.cn/api/front/user/expert/resultsOf");
        /** 获取当前系统时间戳*/
        long timestamp = System.currentTimeMillis();
        /** 生成Base64转码后的参数authorization*/
        String name = 567668+":"+timestamp;
        byte[] bytes = name.getBytes();
        String authorization = Base64.encodeBase64String(bytes);
        /** 生成加密参数sig*/
        String sig = MD5Util.getMD5(567668 + "7d22b0d568ba4fe1ac4e842ec98de9cd" + timestamp);
        /** 生成最终接口访问地址*/
        url = url + "/" + 567668 + "/" + sig;
        String body = JSON.toJSONString(bindBodyAxb);
        /** 调用接口*/
        HttpsService httpsService = new HttpsService();
        String result = httpsService.doPost(url, authorization, body, "UTF-8");
        System.out.println("------------------"+result);
        return str;
    }
}
